package controllers

import (
	"are-you-hungry-db/models"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
)

type FoodController struct {
	beego.Controller
}

func (c *FoodController) Create() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Methods", "*")
	c.Ctx.Output.Header("Access-Control-Allow-Headers", "*")
	if c.Ctx.Input.Method() == "OPTIONS" {
		c.Ctx.Output.SetStatus(200)
		c.StopRun()
	}
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	image, err := models.GetInage(c.GetFile("image"))
	if err != nil {
		r := fmt.Sprintf("%e", err)
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  r,
		}
		c.ServeJSON()
		return
	}
	var food models.Food
	food.Name = name
	food.Price = price
	food.Image = image
	if err := food.CreateFood(); err != nil {
		c.Data["json"] = map[string]any{
			"Code": 500,
			"Msg":  "服务器繁忙",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]any{
		"Code": 200,
		"Msg":  "上传成功",
	}
	c.ServeJSON()
}
